//
//  DMUserViewModel.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/2/29.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit
import AFNetworking

class DMUserViewModel: NSObject {

    static let shareInstance = DMUserViewModel()
    
    var model:DMLoginModel?
    
    /** 修改属性的Get方法 */
    var access_token:String?{
        print("=====")
        print(model?.access_token)
        return model?.access_token
    }
    
    /** 增添一个属性：判断是否已经登陆过 */
    var isLogin:Bool{
        get{
            
             model = DMLoginModel.readObject("info.aaaaa")
            return  model?.access_token == nil ?false : true
        }
    }
    
//MARK:/** 利用Code返回Token的方法 */
    func loadToken(code:String,successBlock:()->(),failureBlock:()->())
    {
        /** 利用第三方框架，构建网络请求 */
        let afn = AFHTTPSessionManager()
        
        let parmet = ["client_id":App_KEY,
            "client_secret":APP_SECERT,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":App_URL
        ]
        
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: parmet, progress: nil, success: { (_,JSON) -> Void in
            /** 成功返回之后 -- 解析JSON数据 */
            if let result = JSON as?[String:NSObject]{
                
                let usrModel = DMLoginModel(dic: result)
            
                self.getPersonInfo(usrModel, successBlock: successBlock, failureBlock: failureBlock)
            }
            
            
            }) { (_,error) -> Void in
                print("====Error====")
                print(error)
                print("====Error====")
                failureBlock()
        }
    }
    
//MARK:/** 利用返回的Token去网络申请加载个人数据 */
    func getPersonInfo(userModel:DMLoginModel,successBlock:()->(),failureBlock:()->()){
        
        let afn = AFHTTPSessionManager()
        
        let paramet = ["access_token":userModel.access_token ?? "",
            "uid":userModel.uid ?? ""
        ]
        
        /** 网络加载数据 */
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: paramet, progress: nil, success: { (_, JSON) -> Void in
            
            if let dic = JSON as? [String:NSObject]{
                userModel.profile_image_url = dic["profile_image_url"] as?String
                userModel.screen_name = dic["screen_name"] as? String
                // 储存信息文件
                print("存储信息")
                userModel.save("info.aaaaa")
                
                self.model = DMLoginModel.readObject("info.aaaaa")
                
                // 回调成功应答
                successBlock()
//                print(NSHomeDirectory())
             }
            
           }) { (_, ERROR) -> Void in
                print("===ERROR===")
                print(ERROR)
                print("===ERROR===")
                failureBlock()
        }
        
    }
    

}
